/*
 * Copyright (C) 2017 yixun All Rights Reserved.
 * 
 * CommissionServiceImpl.java
 */
package com.yixun.qfbao.service.impl;

import com.yixun.common.page.Page;
import com.yixun.qfbao.mapper.CommissionMapper;
import com.yixun.qfbao.mapper.CommissionRulesMapper;
import com.yixun.qfbao.model.Commission;
import com.yixun.qfbao.model.CommissionRules;
import com.yixun.qfbao.model.dto.CommissionDto;
import com.yixun.qfbao.model.dto.CommissionRulesDto;
import com.yixun.qfbao.model.enums.CommisionModeEnum;
import com.yixun.qfbao.model.enums.FollowTypeEnum;
import com.yixun.qfbao.service.CommissionService;
import com.yixun.qfbao.xf.mapper.CustomerPremisesMapper;
import com.yixun.qfbao.xf.mapper.FollowUpListMapper;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.dto.FollowUpListDto;
import com.yixun.qfbao.xf.model.enums.CommissionStatusEnum;
import com.yixun.qfbao.xf.model.enums.FollowUpEnum;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * [文件名称]<br>
 * CommissionServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 *  service interface impl<br>
 * <br>
 * [修改记录]<br>
 * 2017-10-26 15:35:03 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Service("commissionService")
public class CommissionServiceImpl implements CommissionService {
	
	@Autowired
	private CommissionMapper mapper;
	@Autowired
	private CustomerPremisesMapper customerPremisesMapper;
	@Autowired
	private FollowUpListMapper followUpListMapper;
	@Autowired
	private CommissionRulesMapper commissionRulesMapper;
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<Commission> getPageModel(CommissionDto entity,int begin,int end){
		Integer total = mapper.count(entity);
		List<Commission> rows = mapper.list(entity,begin,end);
	    Page<Commission> msr = new Page<Commission>(total, rows);
		return msr;
	}

	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<Commission> selectListByDto(CommissionDto entity){
		return mapper.selectListByDto(entity);
	}
	
	/**
	 * 查询单个
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public Commission selectByDto(CommissionDto entity){
		return mapper.selectByDto(entity);
	}
	
	/**
	 * @param id 搜索条件
	 * @return 分页记录
	 */
	public Commission selectById(Long id){
		if(id!=null){
			return mapper.selectById(id);
		}
		return null;
	}
	/**
	 * @param entity 新增记录的详细信息
	 * @return 新增行数
	 */
	public CommissionDto create(CommissionDto entity) {
		entity.setCreateTime(Calendar.getInstance().getTime());
		mapper.add(entity);
		return entity;
	}

	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	public int update(CommissionDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edit(entity);
	}
    
	/**
	 * @param entity 待删除的记录信息
	 * @return 删除行数
	 */
	public int destroy(CommissionDto entity) {
		return mapper.del(entity);
	}
	
	/**
	 * @param entity 新增或更新
	 * @return 新增行数
	 */
	public int saveOrUpdate(CommissionDto entity) {
		if(entity!=null&&entity.getId()!=null){
			return update(entity);
		}else{
			create(entity);
			return 1;
		}
	}
	
	/**
	 * @param entity 根据pojo搜索如果主键为空则返回它本身
	 * @return 一行记录或本身
	 */
	@Override
	public Commission selectBy(Commission entity) {
		if(entity!=null&&entity.getId()!=null){
			return mapper.selectById(entity.getId());
		}
		return entity;
	}

	/**
	 * 2019.2.22 新增驻守人员仅能看到自己楼盘的佣金的权限
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return
	 */
	@Override
	public Page<CommissionDto> getMyPageModel(CommissionDto entity, int begin,
			int end,String accountType,String partnerId) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Integer total = 0;
		List<CommissionDto> rows = null;
		if("0".equals(accountType)){
			total = mapper.myCount(entity);
			rows = mapper.myList(entity,begin,end);
		}else{
			total = mapper.selectCommissionForCaseMemberCount(entity,partnerId);
			rows = mapper.selectCommissionForCaseMember(entity,begin,end,partnerId);
		}
		for(CommissionDto row:rows){
			if(StringUtils.isNotBlank(row.getCommissionRuleId())){
				String settmentCycle = getRuleSettlementCycle(row.getCommissionRuleId());
				if(StringUtils.isNotBlank(settmentCycle)){
					row.setSettlementCycle(settmentCycle);
				}
			}
			if(row.getPendingDate()!=null){
				row.setPendingDateStr(sdf.format(row.getPendingDate()));
			}
			if(row.getActualDate()!=null){
				row.setActualDateStr(sdf.format(row.getActualDate()));
			}
			if(StringUtils.isNotBlank(row.getCommissionStatus())){
				row.setCommissionStatus(CommissionStatusEnum.getByNo(row.getCommissionStatus()).getDes());
			}
			if(CommissionStatusEnum.has_commission.getDes().equals(row.getCommissionStatus())){
				//已结佣，隐藏结佣按钮
				row.setPendingBtn("0");
			}else{
				if(row.getPendingDate()!=null){
					if(Calendar.getInstance().getTime().getTime()>=row.getPendingDate().getTime()){
						//大于等于待结佣日期，显示结佣按钮
						row.setPendingBtn("1");
					}else{
						row.setPendingBtn("0");
					}
				}else{
					//待结算日期为空，说明没有设置规则，如果未结佣就显示按钮
					row.setPendingBtn("1");
				}
			}
		}
	    Page<CommissionDto> msr = new Page<CommissionDto>(total, rows);
		return msr;
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED)
	public Map<String, String> dealCommission(Long commissionId,
			String commissionType, Double commission, String remark,Long settmentUserId) {
			Map<String,String> map = new HashMap<String, String>();
			if(settmentUserId==null||commissionId==null||StringUtils.isBlank(commissionType)){
				map.put("result", ResultEnum.FAIL.getNo());
				map.put("errorMsg", "参数信息不全，操作失败");
				return map;
			}
			Date date = Calendar.getInstance().getTime();
			Commission entity =  new Commission();
			entity.setId(commissionId);
			entity.setActualDate(date);
			entity.setSettlementUserId(settmentUserId);
			entity.setCommissionStatus(CommissionStatusEnum.has_commission.getNo());
			if(commission!=null){
				entity.setActualCommission(new BigDecimal(commission));
			}
			entity.setUpdateTime(date);
			entity.setUpdateUserId(settmentUserId);
			if("2".equals(commissionType)){
				entity.setReason(remark);
			}
			mapper.edit(entity);
			//把佣金分给符合规则的各个客户
			Commission commissionEntity = mapper.selectById(commissionId);
			CommissionRules commissionRule = getCommissionRules(commissionEntity);
			boolean flag = false;
			if(commissionRule!=null&&CommisionModeEnum.COMMISION_MODE_2.getNo().equals(commissionRule.getCommissionType())||CommisionModeEnum.COMMISION_MODE_4.getNo().equals(commissionRule.getCommissionType())||CommisionModeEnum.COMMISION_MODE_3.getNo().equals(commissionRule.getCommissionType())){
				//当按固定比例和阶梯总额计算时，佣金的计算拿成交的总额除以机构总金额乘以佣金值
				flag = true;
			}
			CustomerPremisesDto cDto = new CustomerPremisesDto();
			cDto.setCommissionId(commissionId);
			cDto.setSql("rules_id is not null");
			List<CustomerPremises> list = customerPremisesMapper.selectListByDto(cDto);
			int cusNum = list.size();
			BigDecimal average = new BigDecimal(0);
			if(commission!=null&&commission!=0&&cusNum>0){
				//计算平均佣金，保留两位小数
				DecimalFormat df = new DecimalFormat("0.00");
				average = new BigDecimal(df.format(commission*1.0/(cusNum*1.0)));
			}
			//分配佣金，标记为已结佣，跟进表记录结佣记录
			for(CustomerPremises customerPremises:list){

				String commissionStatus = customerPremises.getCommissionStatus();
				if(CommissionStatusEnum.out_commission.getNo().equals(commissionStatus)){
					continue;
				}

				CustomerPremises cus = new CustomerPremises();
				cus.setCommissionStatus(CommissionStatusEnum.has_commission.getNo());
				if(flag){
					//说明按固定比例或者是按阶梯总额平分佣金
					if(commission!=null&&commission!=0&&customerPremises.getDealAmount()!=null&&StringUtils.isNotBlank(commissionEntity.getDealAmount())){
							BigDecimal decimal = new BigDecimal(commission);
							BigDecimal commissionAmount = decimal.multiply(customerPremises.getDealAmount()).divide(new BigDecimal(commissionEntity.getDealAmount()),2,BigDecimal.ROUND_HALF_UP);
							cus.setCommissionAmount(String.valueOf(commissionAmount));
					}
				}else{
					cus.setCommissionAmount(String.valueOf(average));
				}
				cus.setId(customerPremises.getId());
				customerPremisesMapper.edit(cus);
				// 新增跟进信息
				FollowUpListDto follow = new FollowUpListDto();
				follow.setStaffId(settmentUserId);
				follow.setCustomerPremisesId(customerPremises.getId());
				follow.setCreateTime(Calendar.getInstance().getTime());
				follow.setOldConfirmStatus(customerPremises.getConfirmStatus());
				follow.setNewConfirmStatus(customerPremises.getConfirmStatus());
				follow.setOldCustomerStatus(customerPremises.getCustomerStatus());
				follow.setNewCustomerStatus(customerPremises.getCustomerStatus());
				follow.setOldCommissionStatus(customerPremises.getCommissionStatus());
				follow.setNewCommissionStatus(CommissionStatusEnum.has_commission.getNo());
				follow.setRemark("【变更佣金状态】");
				follow.setFollowUpType(FollowUpEnum.status_transfer.getNo());
				follow.setFollowType(FollowTypeEnum.DEVELOPERS.getNo());
				follow.setTargetPremisesId(customerPremises.getPremisesId());
				followUpListMapper.add(follow);
			}
			CustomerPremisesDto cDto2 = new CustomerPremisesDto();
			cDto2.setCommissionId(commissionId);
			cDto2.setSql("rules_id is null");
			List<CustomerPremises> list2 = customerPremisesMapper.selectListByDto(cDto2);
			for(CustomerPremises cus2:list2){
				String commissionStatus = cus2.getCommissionStatus();
				if(CommissionStatusEnum.out_commission.getNo().equals(commissionStatus)){
					continue;
				}
				//更新已设置报备规则但没有匹配到规则的报备记录(包含无规则的)
				CustomerPremises cu = new CustomerPremises();
				//判断是否是无规则的但是有佣金值,则按 每套的成交总额除以机构的总成交金额再乘以佣金
				if(commissionEntity.getPendingDate()==null&&StringUtils.isBlank(commissionEntity.getSettlementCycle())
						&&commission!=null&&commission!=0&&cus2.getDealAmount().compareTo(BigDecimal.ZERO)!=0
						&&cus2.getDealAmount()!=null&&StringUtils.isNotBlank(commissionEntity.getDealAmount())&&!"0".equals(commissionEntity.getDealAmount())){
						
					BigDecimal commissionAmount = cus2.getDealAmount().
									multiply(new BigDecimal(commission)).divide(new BigDecimal(commissionEntity.getDealAmount()),2,BigDecimal.ROUND_HALF_UP);
					cu.setCommissionAmount(String.valueOf(commissionAmount));
				}
				cu.setId(cus2.getId());
				cu.setCommissionStatus(CommissionStatusEnum.has_commission.getNo());
				customerPremisesMapper.edit(cu);
				// 新增跟进信息
				FollowUpListDto follow2 = new FollowUpListDto();
				follow2.setStaffId(settmentUserId);
				follow2.setCreateTime(Calendar.getInstance().getTime());
				follow2.setCustomerPremisesId(cu.getId());
				follow2.setOldConfirmStatus(cu.getConfirmStatus());
				follow2.setNewConfirmStatus(cu.getConfirmStatus());
				follow2.setOldCustomerStatus(cu.getCustomerStatus());
				follow2.setNewCustomerStatus(cu.getCustomerStatus());
				follow2.setOldCommissionStatus(cu.getCommissionStatus());
				follow2.setNewCommissionStatus(CommissionStatusEnum.has_commission.getNo());
				follow2.setRemark("【变更佣金状态】");
				follow2.setFollowUpType(FollowUpEnum.status_transfer.getNo());
				follow2.setFollowType(FollowTypeEnum.DEVELOPERS.getNo());
				followUpListMapper.add(follow2);
			}
			map.put("result", "1");
			map.put("msg", "操作成功");
		return map;
	}

	@Override
	public CommissionDto selectByMyId(Long id) {
		CommissionDto commission = mapper.selectByMyId(id);
		if(commission!=null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(commission.getActualDate()!=null){
				commission.setActualDateStr(sdf.format(commission.getActualDate()));
			}
			if(StringUtils.isNotBlank(commission.getCommissionStatus())){
				commission.setCommissionStatus(CommissionStatusEnum.getByNo(commission.getCommissionStatus()).getDes());
			}
			if(commission.getPendingDate()!=null){
				commission.setPendingDateStr(sdf.format(commission.getPendingDate()));
			}
		}
		return commission;
	}
	
	/**
	 * 根据机构ID和楼盘ID还有佣金状态等信息查询佣金表
	 * @param commissionDto
	 * @return Commission
	 * @author shaoping.jiao
	 */
	public Commission selectByCompanyIdAndPremisesId(@Param("commissionDto")CommissionDto commissionDto) {
		return mapper.selectByCompanyIdAndPremisesId(commissionDto);
	};
	
	/**
	 * 新增佣金
	 * @param commission
	 * @return
	 * @author shaoping.jiao
	 */
	public int add(Commission commission) {
		return mapper.add(commission);
	}
	
	/**
     * 编辑
     * @param commission 需要编辑的BEAN信息
     */
    public int edit(Commission commission) {
    	return mapper.edit(commission);
    };
    /**
     * 获取佣金表对应的规则
     *@author xiaojin.li
     *@date 2017年11月1日下午3:59:35
     *@param commission
     *@return
     */
    public CommissionRules getCommissionRules(Commission commission){
    	if(commission!=null&&commission.getBeginTime()!=null){
    		CommissionRulesDto dto = new CommissionRulesDto();
        	dto.setGroupId(commission.getCommissionRuleId());
        	List<CommissionRules> list = commissionRulesMapper.selectListByDto(dto);
        	if(list.size()>=1){
        		return list.get(0);
        	}else{
        		//当没有规则时返回个空对象
        		return new CommissionRules();
        	}
    	}else{
    		//当没有规则时返回个空对象
    		return new CommissionRules();
    	}
    }
    /**
     * 根据规则字表的groupID获取规则的结算周期
     *@author xiaojin.li
     *@date 2017年11月7日下午5:30:28
     *@param groupId
     *@return
     */
    public String getRuleSettlementCycle(String groupId){
    	String str = "";
    	if(StringUtils.isNotBlank(groupId)){
    		CommissionRulesDto ruls = new CommissionRulesDto();
    		ruls.setGroupId(groupId);
    		//ruls.setDelFlag(DelFlagEnum.UNDEL.getNo());
    		//ruls.setState("1");
    		List<CommissionRules> list = commissionRulesMapper.selectListByDto(ruls);
    		if(list!=null&&list.size()>0){
    			CommissionRules commissionRules = list.get(0);
    			if(commissionRules!=null){
    				if(CommisionModeEnum.COMMISION_MODE_1.getNo().equals(commissionRules.getCommissionType())
    						||CommisionModeEnum.COMMISION_MODE_2.getNo().equals(commissionRules.getCommissionType())){
    					//按固定的
    					return "T+"+commissionRules.getSettlementCycle();
    				}else if(CommisionModeEnum.COMMISION_MODE_3.getNo().equals(commissionRules.getCommissionType())
    						||CommisionModeEnum.COMMISION_MODE_4.getNo().equals(commissionRules.getCommissionType())){
    					//按阶梯
    					if("30".equals(commissionRules.getSettlementCycle())){
    						return "月结算(默认为每月的10号)";
    					}
    					if("90".equals(commissionRules.getSettlementCycle())){
    						return "季度结算(默认为下一季度第一个月的10号)";
    					}
    				}else{
    					return "";
    				}
    			}
    		}
    	}
    	return str;
    }
}
